package cn.edu.nwpu.warehousemanagement.service.impl;

import cn.edu.nwpu.warehousemanagement.constantEnum.UserRole;
import cn.edu.nwpu.warehousemanagement.dao.UserRepository;
import cn.edu.nwpu.warehousemanagement.pojo.Result;
import cn.edu.nwpu.warehousemanagement.pojo.User;
import cn.edu.nwpu.warehousemanagement.pojo.request.AdminUpdateUserInfoRequest;
import cn.edu.nwpu.warehousemanagement.service.AdminService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Admin服务实现
 *
 * @author Loadstar
 * @version 1.0
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private UserRepository userRepository;

    @Override
    public Result<?> deleteUser(Long userId) {
        try {
            userRepository.deleteById(userId);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }

    @Override
    public Result<?> updateUserInfo(AdminUpdateUserInfoRequest updateUserInfoRequest) {
        try {
            Long userId = updateUserInfoRequest.getId();
            String realname = updateUserInfoRequest.getRealname();
            String phone = updateUserInfoRequest.getPhone();
            String email = updateUserInfoRequest.getEmail();
            UserRole role = updateUserInfoRequest.getRole();
            // 检查用户是否存在
            if (!userRepository.existsById(userId)) {
                return Result.error("用户不存在");
            }

            userRepository.updateUserById(userId, realname, phone, email, role);


            return Result.success("更新成功");
        } catch (Exception e) {
            throw new RuntimeException("更新失败", e);
        }
    }

    @Override
    public Result<?> findAllUser(Pageable pageable) {
        Page<User> users = userRepository.findAllNotDeleted(pageable);
        return Result.success(users);
    }
}
